import {
  createRouter,
  createWebHashHistory
  // createWebHistory
  // Router
} from "vue-router";
// import { ElNotification } from "element-plus";
// import { openLink } from "/@/utils/link";

// import homeRouter from "./modules/home";
// import editorRouter from "./modules/editor";
// import componentsRouter from "./modules/components";
// import nestedRouter from "./modules/nested";
import errorRouter from "./modules/error";
// import reportRouter from "./modules/report"; // 报表页面
// import fileRouter from "./modules/file"; // 文档管理
// import flowRouter from "./modules/flow"; // 流程管理
// import systemRouter from "./modules/system";
// import projectRouter from "./modules/project"; // 项目管理
// import processRouter from "./modules/process"; // 进度管理
// import qualityRouter from "./modules/quality"; // 质量管理
// import modifyRouter from "./modules/modify"; // 变更管理
// import testRouter from "./modules/testRouter"; // 测试管理
// import acceptanceRouter from "./modules/acceptance"; // 验收管理
// import workRouter from "./modules/work"; // 工作台管理expert
// import expertRouter from "./modules/expert"; // 专家管理
// import reviewRouter from "./modules/review"; // 评审管理
// import projectRouter from "./modules/project"; // 管理
// import teamRouter from "./modules/team"; // 管理
// import systemRouter from "./modules/system"; // 系统管理

import remainingRouter from "./modules/remaining"; //静态路由

import { storageLocal } from "../utils/storage";
// import { i18n } from "/@/plugins/i18n";
import { usePermissionStoreHook } from "/@/store/modules/permission";

// import { getAsyncRoutes } from "/@/api/mock";
import { getAsyncRoutes } from "/@/api/menu";

import Layout from "/@/layout/index.vue";
// https://cn.vitejs.dev/guide/features.html#glob-import
let modulesRoutes = import.meta.glob("/src/views/*/*/*.vue");
const modulesRoutes2 = import.meta.glob("/src/views/*/*/*/*.vue");
// const modulesRoutes3 = import.meta.glob("/src/views/*/*/*/*/*.vue");
modulesRoutes = Object.assign(modulesRoutes, modulesRoutes2);
// modulesRoutes = Object.assign(modulesRoutes, modulesRoutes3);

const constantRoutes: Array<any> = [
  // homeRouter,
  // expertRouter,
  // reviewRouter,
  // projectRouter,
  // teamRouter,
  // workRouter
  // projectRouter,
  // processRouter,
  // qualityRouter,
  // modifyRouter,
  // flowRouter,
  // editorRouter,
  // componentsRouter,
  // acceptanceRouter
  // nestedRouter
  // reportRouter,
  // fileRouter
  errorRouter
];
// constantRoutes = constantRoutes.concat(...systemRouter);

// 按照路由中meta下的rank等级升序来排序路由
export const ascending = arr => {
  // return arr.sort((a: any, b: any) => {
  //   return a?.meta?.rank - b?.meta?.rank;
  // });
  return arr;
};

// 过滤meta中showLink为false的路由
export const filterTree = data => {
  const newTree = data.filter(
    (v: { meta: { showLink: boolean } }) => v.meta.showLink
  );
  newTree.forEach((v: { children }) => {
    v.children && (v.children = filterTree(v.children));
  });
  return newTree;
};

// 将所有静态路由导出
export const constantRoutesArr = ascending(constantRoutes).concat(
  ...remainingRouter
);

// 过滤后端传来的动态路由重新生成规范路由
function childrenRouter(children: Array<string>) {
  if (!children || !children.length) return;
  children.forEach((k: any) => {
    k.component = modulesRoutes[`/src/views${k.path}/index.vue`];
    // TODO , 是否设置动态路由白名单
    // if (k.path === "/project/detail") {
    //   k.path = "/project/detail/:id";
    //   k.props = true;
    // }
    if (k.children?.length) {
      childrenRouter(k.children);
    }
  });
}

export const initAsyncRoutes = (children: Array<string>) => {
  if (!children || !children.length) return;
  children.forEach((k: any) => {
    k.path = k.menuPath;
    k.name = k.menuCode;
    k.meta = {
      icon: k.icon,
      title: k.menuName,
      showLink: k.isDisplay === "Y" ? true : false,
      // showLink: true,
      rank: k.menuOrder,
      savedPosition: false,
      activeMenu: k.menuUrl
      // activeMenu: k.isDisplay === "Y" ? "" : `/${k.menuPath.split("/")[1]}`
    };
    if (k.children && k.children?.length) {
      const filterMenu = k.children.filter(item => {
        return item.isDisplay === "Y";
      });
      if (filterMenu?.length) {
        k.redirect = filterMenu.length && filterMenu[0].menuPath;
      }
    }

    if (k.children && k.children?.length) {
      initAsyncRoutes(k.children);
    }
  });
  return children;
};

export const addAsyncRoutes = (arrRoutes: Array<string>) => {
  if (!arrRoutes || !arrRoutes.length) return;
  arrRoutes.forEach((v: any) => {
    // if (v.redirect) {
    v.component = Layout;
    // } else {
    //   v.component = modulesRoutes[`/src/views${v.path}/index.vue`];
    // }
    if (v.children?.length) {
      childrenRouter(v.children);
    }
  });
  return arrRoutes;
};

const router = createRouter({
  // history: createWebHistory(import.meta.env.VITE_BASE as any),
  history: createWebHashHistory(import.meta.env.VITE_BASE as any),
  routes: ascending(constantRoutes).concat(...remainingRouter),
  scrollBehavior(to, from, savedPosition) {
    return new Promise(resolve => {
      if (savedPosition) {
        return savedPosition;
      } else {
        if (from.meta.saveSrollTop) {
          const top: number =
            document.documentElement.scrollTop || document.body.scrollTop;
          resolve({ left: 0, top });
        }
      }
    });
  }
});

/**
 * 从后台请求路由信息。并动态加入路由实例中
 * */
export const initRouter = (next?, to?) => {
  return new Promise(resolve => {
    getAsyncRoutes({})
      .then(res => {
        let info = [];
        if (res.code === 200) {
          info = res?.data ?? [];
          if (info.length) {
            info = initAsyncRoutes(info);
          }
        }

        if (info && info.length === 0) {
          usePermissionStoreHook().changeSetting(info);
        } else {
          addAsyncRoutes(info).map((v: any) => {
            // 防止重复添加路由
            // console.log("v", v);
            if (
              router.getRoutes().findIndex(value => value.path === v.path) !==
              -1
            ) {
              // usePermissionStoreHook().changeSetting(info);
              return;
            } else {
              // 切记将路由push到routes后还需要使用addRoute，这样路由才能正常跳转
              if (v?.path) {
                router.options.routes.forEach(item => {
                  if (item.path === v.path) {
                    router.options.routes.push(v);
                  }
                });
              }
              // 最终路由进行升序
              ascending(router.options.routes);
              if (v.name !== "") {
                router.addRoute(v.name, v);
              }

              if (next && to) next({ ...to, replace: true });
              usePermissionStoreHook().changeSetting(info);
            }

            resolve({ router, info });
          });
        }
        // router.addRoute({
        //   path: "/:pathMatch(.*)",
        //   redirect: "/"
        // });
      })
      .catch(error => {
        console.log(error)
        const code = error?.response?.status;
        if ([401, 403].includes(code)) {
          storageLocal.removeItem("rdms-info");
          router.push("/login");
        }
      });
  });
};

// reset router
const whiteList = [
  "/login",
  "/logout",
  "/register",
  "/",
  "/welcome",
  "/search",
  "/home",
  "/:pathMatch(.*)",
  "/error/401",
  "/error/404",
  "/error",
  "/redirect",
  "/profile",
  "/redirect/:path(.*)",
  "/search/manage",

  "/online"
  // "/testrouter(.*)"
];

export function resetRouter() {
  router.getRoutes().forEach(route => {
    const { name } = route;
    if (name && !whiteList.includes(route.path)) {
      router.hasRoute(name) && router.removeRoute(name);
    }
  });
}

import NProgress from "../utils/progress";

router.beforeEach(async (to, _from, next) => {
  // console.log(to, _from);
  NProgress.start();
  const name = storageLocal.getItem("rdms-info")?.name ?? "";

  if (name) {
    if (["/login", "/logout"].includes(to.path)) {
      next();
      // storageLocal.removeItem("rdms-info");
    } else {
      try {
        const res = await usePermissionStoreHook().getBtnAuth(
          to.path as string,
          to.query as any
        );
        console.log(res, "res");
        // if (!res) {
        //   await Promise.reject("出错了");
        // }
        if (res && usePermissionStoreHook().wholeRoutes.length === 0) {
          //   initRouter(next, to).then((router: Router) => {
          //     router.push(to.path);
          //   });

          const obj: any = await initRouter();
          if (obj.info && getRouterAuth(obj.info, to.path)) {
            if (to.path === "/") {
              obj.router.push({
                path: obj.info[0].children[0].menuPath
              });
            } else {
              obj.router.push({ path: to.path, query: to.query });
            }
          } else {
            if (to.path === "/") {
              obj.router.push({
                path: "/project/kanban"
              });
            } else {
              obj.router.push({
                path: "/error"
              });
            }
          }
        }

        next();
      } catch (err) {
        console.error(err);
      }
    }
  } else {
    if (to.path !== "/login") {
      if (to.path === "/project/kanban") {
        const res = await usePermissionStoreHook().getBtnAuth(
          to.path as string,
          to.query as any
        );
        if (res && usePermissionStoreHook().wholeRoutes.length === 0) {
          setTimeout(async () => {
            const obj: any = await initRouter();
            if (obj.info && getRouterAuth(obj.info, to.path)) {
              obj.router.push({ path: to.path, query: to.query });
            } else {
              if (to.path === "/") {
                obj.router.push({
                  path: "/project/kanban"
                });
              } else {
                obj.router.push({
                  path: "/error"
                });
              }
            }
          }, 500);
        }
      } else {
        next({ path: "/login" });
      }
    } else {
      next();
    }

    // storageLocal.removeItem("rdms-info");

    usePermissionStoreHook().resetSetting();
    resetRouter();
  }
});

function getRouterAuth(nodes, searchKey) {
  if (searchKey === "/online") {
    return searchKey;
  }
  for (let _i = 0; _i < nodes.length; _i++) {
    if (nodes[_i].menuPath === searchKey) {
      return nodes[_i];
    } else {
      if (nodes[_i].children && nodes[_i].children.length > 0) {
        const res = getRouterAuth(nodes[_i].children, searchKey);
        if (res) {
          return res;
        }
      }
    }
  }
  return null;
}

router.afterEach(() => {
  NProgress.done();
});

export default router;
